<template>
  <view class="review-edit-container">
    <view class="page-header">
      <text class="page-title">编辑评价</text>
      <text class="page-subtitle">修改评价信息</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <view class="form-section">
        <text class="section-title">评价者信息</text>
        
        <view class="form-item">
          <text class="form-label required">评价者ID</text>
          <uni-easyinput 
            v-model="formData.reviewer_id"
            placeholder="请输入评价者ID"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.reviewer_id" class="error-text">{{ errors.reviewer_id }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">预约ID</text>
          <uni-easyinput 
            v-model="formData.appointment_id"
            placeholder="关联的预约ID（选填）"
            :clearable="true"
            trim="all"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">评价对象</text>
        
        <view class="form-item">
          <text class="form-label required">评价类型</text>
          <radio-group @change="onReviewTypeChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.review_type === 1" color="#007aff"/>
              <text class="radio-text">医生</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.review_type === 2" color="#007aff"/>
              <text class="radio-text">服务</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.review_type === 3" color="#007aff"/>
              <text class="radio-text">产品</text>
            </label>
          </radio-group>
        </view>

        <view class="form-item">
          <text class="form-label required">评价对象ID</text>
          <uni-easyinput 
            v-model="formData.reviewed_item_id"
            :placeholder="'请输入' + reviewTypeText + 'ID'"
            :clearable="true"
            trim="all"
          />
          <text v-if="errors.reviewed_item_id" class="error-text">{{ errors.reviewed_item_id }}</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">评价内容</text>
        
        <view class="form-item">
          <text class="form-label required">评分（1-5星）</text>
          <view class="star-rating">
            <view 
              v-for="star in 5" 
              :key="star" 
              class="star-item" 
              @click="selectRating(star)"
            >
              <text class="star-icon" :class="{ active: star <= formData.rating }">★</text>
            </view>
            <text class="rating-text">{{ formData.rating }} 星</text>
          </view>
          <text v-if="errors.rating" class="error-text">{{ errors.rating }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">评价内容</text>
          <textarea 
            v-model="formData.content" 
            class="form-textarea" 
            placeholder="请输入评价内容"
            maxlength="500"
          />
          <text v-if="errors.content" class="error-text">{{ errors.content }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">评价图片（最多9张）</text>
          <uni-file-picker 
            v-model="imagesFileList"
            file-mediatype="image"
            mode="grid"
            :limit="9"
            :auto-upload="false"
            @select="handleImagesSelect"
            @delete="handleImageDelete"
          />
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">其他设置</text>
        
        <view class="form-item">
          <text class="form-label">状态</text>
          <radio-group @change="onIsHiddenChange" class="radio-group">
            <label class="radio-item">
              <radio value="false" :checked="!formData.is_hidden" color="#007aff"/>
              <text class="radio-text">显示</text>
            </label>
            <label class="radio-item">
              <radio value="true" :checked="formData.is_hidden" color="#007aff"/>
              <text class="radio-text">隐藏</text>
            </label>
          </radio-group>
        </view>

        <view v-if="formData.is_hidden" class="form-item">
          <text class="form-label">隐藏原因</text>
          <textarea 
            v-model="formData.hidden_reason" 
            class="form-textarea" 
            placeholder="请输入隐藏原因"
            maxlength="200"
          />
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const pageLoading = ref(true)
const reviewId = ref('')

const formData = reactive({
  reviewer_id: '',
  appointment_id: '',
  review_type: 1,
  reviewed_item_id: '',
  rating: 5,
  content: '',
  images: [],
  is_hidden: false,
  hidden_reason: ''
})

const errors = reactive({
  reviewer_id: '',
  reviewed_item_id: '',
  rating: '',
  content: ''
})

const imagesFileList = ref([])
const originalImages = ref([])

const reviewTypeText = computed(() => {
  const typeMap = {
    1: '医生',
    2: '服务',
    3: '产品'
  }
  return typeMap[formData.review_type] || ''
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  reviewId.value = currentPage.options.id || ''
  
  if (!reviewId.value) {
    uni.showToast({ title: '缺少评价ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/reviews/list' })
    }, 1500)
    return
  }
  
  await loadReviewData()
  pageLoading.value = false
})

async function loadReviewData() {
  try {
    // 调用云对象方法获取评价信息
    const reviewsObj = uniCloud.importObject('dh-reviews')
    const result = await reviewsObj.getReviewById(reviewId.value)
    
    if (result.code === 200 && result.data) {
      const data = result.data
      Object.assign(formData, {
        reviewer_id: data.reviewer_id || '',
        appointment_id: data.appointment_id || '',
        review_type: data.review_type || 1,
        reviewed_item_id: data.reviewed_item_id || '',
        rating: data.rating || 5,
        content: data.content || '',
        images: data.images || [],
        is_hidden: data.is_hidden || false,
        hidden_reason: data.hidden_reason || ''
      })
      
      if (data.images && data.images.length > 0) {
        originalImages.value = data.images
        imagesFileList.value = data.images.map((url, index) => ({ url, name: `图片${index + 1}` }))
      }
    } else {
      throw new Error(result.message || '评价不存在')
    }
  } catch (err) {
    console.error('加载评价数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/reviews/list' })
    }, 1500)
  }
}

function onReviewTypeChange(e) {
  formData.review_type = parseInt(e.detail.value)
}

function onIsHiddenChange(e) {
  formData.is_hidden = e.detail.value === 'true'
  if (!formData.is_hidden) {
    formData.hidden_reason = ''
  }
}

function selectRating(star) {
  formData.rating = star
  errors.rating = ''
}

function handleImagesSelect(e) {
  if (e.tempFiles && e.tempFiles.length > 0) {
    imagesFileList.value = e.tempFiles
  }
}

function handleImageDelete(e) {
  // File picker handles deletion automatically
}

async function uploadImagesToCloud() {
  if (!imagesFileList.value || imagesFileList.value.length === 0) {
    return []
  }
  
  try {
    const uploadPromises = imagesFileList.value
      .filter(file => file.path && !file.url)
      .map(async (file) => {
        const uploadResult = await uniCloud.uploadFile({
          filePath: file.path,
          cloudPath: `reviews/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.${file.name.split('.').pop()}`
        })
        return uploadResult.fileID
      })
    
    const newImageUrls = await Promise.all(uploadPromises)
    
    const existingUrls = imagesFileList.value
      .filter(file => file.url && !file.path)
      .map(file => file.url)
    
    return [...existingUrls, ...newImageUrls]
  } catch (err) {
    console.error('图片上传失败:', err)
    throw err
  }
}

function validateForm() {
  let isValid = true
  
  if (!formData.reviewer_id || formData.reviewer_id.trim().length === 0) {
    errors.reviewer_id = '请输入评价者ID'
    isValid = false
  } else {
    errors.reviewer_id = ''
  }
  
  if (!formData.reviewed_item_id || formData.reviewed_item_id.trim().length === 0) {
    errors.reviewed_item_id = '请输入评价对象ID'
    isValid = false
  } else {
    errors.reviewed_item_id = ''
  }
  
  if (formData.rating < 1 || formData.rating > 5) {
    errors.rating = '请选择1-5星评分'
    isValid = false
  } else {
    errors.rating = ''
  }
  
  if (!formData.content || formData.content.trim().length === 0) {
    errors.content = '请输入评价内容'
    isValid = false
  } else {
    errors.content = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    let imageUrls = originalImages.value || []
    const hasNewImages = imagesFileList.value && imagesFileList.value.length > 0 && imagesFileList.value.some(file => file.path && !file.url)
    
    if (hasNewImages) {
      uni.showLoading({ title: '上传图片中...' })
      imageUrls = await uploadImagesToCloud()
    }
    
    const db = uniCloud.database()
    const submitData = {
      ...formData,
      images: imageUrls,
      update_time: Date.now()
    }
    
    // 调用云对象方法更新评价
    const reviewsObj = uniCloud.importObject('dh-reviews')
    const result = await reviewsObj.updateReview(reviewId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: result.message || '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/reviews/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '更新失败', icon: 'none' })
    }
  } catch (err) {
    console.error('更新失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/reviews/list' })
}
</script>

<style lang="scss" scoped>
.review-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  background: #fff;
  border-radius: 16rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.star-rating {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.star-item {
  cursor: pointer;
}

.star-icon {
  font-size: 60rpx;
  color: #e0e0e0;
  
  &.active {
    color: #ffb400;
  }
}

.rating-text {
  font-size: 28rpx;
  color: #666;
  margin-left: 20rpx;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
